<?php

namespace App\Models\Shop;

use App\Enums\OpenShop\MissionTemplateEnum;
use App\Models\BaseModel;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class ShopModel extends BaseModel
{
    protected $table = "kf_shops";

    const STATUS_OK      = 0; // 正常
    const STATUS_CLOSE   = 1; // 关闭
    const STATUS_PREPARE = 2; // 筹备中


    /**
     * 督导关联数据
     *
     * @return HasOne
     */
    public function councilorRel(): HasOne
    {
        return $this->hasOne(KmsUser::class, "rmsUserId", "councilorId");
    }

    /**
     * @return HasOne
     */
    public function signOrderRel(): HasOne
    {
        return $this->hasOne(OpenShopSignOrderModel::class, "shopCode", "shopCode")->orderByDesc("id");
    }

    public function getDataById(int $shopId): ?self
    {
        return Cache::remember("ShopModel:{$shopId}", 120, function () use ($shopId) {
            return ShopModel::query()->find($shopId);
        });
    }

    /**
     * 获取门店详情
     *
     * @param array $where
     * @return Builder|Model|object|null
     */
    public function getShopInfoByParams(array $where)
    {
        return ShopModel::query()->where($where)->first();
    }

    /**
     * 判断门店是否在筹备中
     *
     * @param int $shopId
     * @return bool
     */
    public static function shopInPrepare(int $shopId): bool
    {
        $shopModel = self::query()->where("id", $shopId)->first();
        // todo  筹备中
        $mainProcess = OpenShopMainProcessModel::query()
                                               ->where('shopId', $shopId)
                                               ->select('id', 'shopId', 'nowStepStatus', 'childLocationOrder')
                                               ->first();

        if (
            attributeGet($shopModel, "status", null) == self::STATUS_PREPARE
            &&
            attributeGet($mainProcess, "nowStepStatus", null) != MissionTemplateEnum::STEP_STATUS_999) {
            return true;
        }
        return false;
    }

    /**
     * 获取多个门店详情
     * @param array $shopIds
     * @param string $field
     * @return array
     */
    public static function getShopInfosByParams(array $shopIds, string $field): array
    {
        return self::query()
                   ->whereIn('id', $shopIds)
                   ->selectRaw($field)
                   ->groupBy('district')
                   ->get()
                   ->map(
                       function ($item) {
                           return $item->province . '-' . $item->city . '-' . $item->district;
                       }
                   )
                   ->toArray();
    }

    /**
     * 根据数据库时间数值得出时间
     *
     * @return string[]
     */
    public function getFormatBusinessTime(): array
    {
        //开始时间取小时
        $startHour = floor($this->startAt / 60);
        $startHour = $startHour >= 10 ? $startHour : "0" . $startHour;
        //开始时间取分钟
        $startMinute = $this->startAt % 60;
        if ($startMinute == 0) {
            $startMinute = '00';
        }
        //结束时间取小时
        $endHour = floor($this->endAt / 60);
        $endHour = $endHour >= 10 ? $endHour : "0" . $endHour;
        //结束时间取分钟
        $endMinute = $this->endAt % 60;
        if ($endMinute == 0) {
            $endMinute = '00';
        }
        //分钟差
        //开始时间
        if ($endHour >= 24) {
            //次日
            $endHour = $endHour - 24;
        }
        return [
            Carbon::createFromTime($startHour, $startMinute),
            Carbon::createFromTime($endHour, $endMinute)
        ];
    }

    /**
     * 通过搜索编号和名称获得门店ID
     */
    public static function getShopIdByGeneralSearch(string $searchStr): array
    {
        if (!strlen($searchStr)) {
            return [];
        }
        return self::query()
            ->where(function ($query) use ($searchStr) {
                if (is_numeric($searchStr)) {
                    $query->where('shopCode', $searchStr);
                } else {
                    $query->where('name', 'like', "%$searchStr%");
                }
            })
            ->pluck('id')
            ->toArray();

    }

}
